var that
class Tab {
  constructor(id) {
    that = this
    this.main = document.querySelector(id)
    this.tabBtn = this.main.querySelector('.tabsbox .tabadd')
    this.ul = this.main.querySelector('.fisrstnav ul')
    this.sectionsFather = this.main.querySelector('.tabscon')
    this.init()
  }

  init() {
    this.updata()
    this.tabBtn.onclick = this.addTabs
    for (var i = 0; i < this.lis.length; i++) {
      this.lis[i].index = i
      this.lis[i].onclick = this.toggleTabs
      this.spans[i].ondblclick = this.editTabs
      this.delBtns[i].onclick = this.delTabs
      this.sections[i].ondblclick = this.editTabs
    }
  }

  updata() {
    this.lis = this.main.querySelectorAll('.fisrstnav li')
    this.sections = this.main.querySelectorAll('.tabscon section')
    this.delBtns = this.main.querySelectorAll('.fisrstnav .icon-guanbi')
    this.spans = this.main.querySelectorAll('.fisrstnav span')
  }

  clearClass() {
    for (var i = 0; i < this.lis.length; i++) {
      this.lis[i].className = ''
      this.sections[i].className = ''
    }
  }
  toggleTabs() {
    that.clearClass()
    this.className = 'liactive'
    that.sections[this.index].className = 'conactive'
    that.init()
  }

  addTabs() {
    that.clearClass()
    var li = `
    <li class="liactive"><span>测试新增</span><span class="iconfont icon-guanbi"></span></li>
    `
    var section = `
    <section class="conactive">测试${Math.random()}</section>
    `
    that.ul.insertAdjacentHTML('beforeend', li)
    that.sectionsFather.insertAdjacentHTML('beforeend', section)
    that.init()
  }

  delTabs(e) {
    e.stopPropagation()
    var index = this.parentNode.index
    that.lis[index].remove()
    that.sections[index].remove()
    if (that.main.querySelector('.liactive')) return
    index--
    // index === -1 ? '' : that.lis[index].click()
    if (index === -1) that.lis[1]?.click()
    that.lis[index]?.click()
  }

  editTabs(e) {
    e.stopPropagation()
    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty()
    var str = this.innerHTML
    this.innerHTML = `<input type="text">`
    var input = this.children[0]
    input.value = str
    input.select()
    input.onblur = function () {
      this.parentNode.innerHTML = input.value
    }
  }
}

new Tab('#tab')
